package com.ruoyi.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.config.RandomUtil;
import com.ruoyi.system.constant.MqttPushClient;
import com.ruoyi.system.domain.LogEntry;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ruoyi
 * @date 2025-01-02
 */
@RestController
@RequestMapping("/sys/autoPull")
public class AutoPullController extends BaseController {

    private static final String hex = "140124013F";
    private final AtomicInteger counter = new AtomicInteger(0);

    @Autowired
    private MqttPushClient mqttPushClient;

    /**
     * 自动拉取并按顺序发送B2, B4, B5帧，每帧之间间隔3秒，B5完成后等待5秒再继续下一轮。
     *
     * @param lists 日志条目列表
     * @return 操作结果
     * @throws MqttException 如果MQTT推送失败
     * @throws InterruptedException 如果线程睡眠被中断
     */
    @GetMapping("/autoPull")
    public void autoPull(@RequestBody List<LogEntry> lists) throws MqttException, InterruptedException {
        for (LogEntry entry : lists) {
            boolean re = executeInstructionSequence(entry);
            if (!re) {
//                return success(false); // 如果任何一次执行失败，则立即返回错误
            }

            // 在b5完成后等待5秒再继续下一次循环
            Thread.sleep(2000);
        }
//        return success(true);
    }

    /**
     * 执行一次完整的指令序列（B2 -> B4 -> B5），每个指令之间间隔3秒。
     *
     * @param entry 日志条目
     * @return 是否所有指令都成功执行
     * @throws MqttException 如果MQTT推送失败
     * @throws InterruptedException 如果线程睡眠被中断
     */
    private boolean executeInstructionSequence(LogEntry entry) throws MqttException, InterruptedException {
        String macId = entry.getObuId();
        String str15 = entry.getIcCard0015();
        String str19 = entry.getIcCard0019();
        String ef01 = entry.getEf01Info();
        String ef04 = entry.getEf04Info();

        boolean res1 = pushB2(macId);
        if (!res1) return false;

        Thread.sleep(2000); // B2和B4之间等待3秒

        boolean res2 = pushB4(macId, str15, str19, ef01, ef04);
        if (!res2) return false;

        Thread.sleep(2000); // B4和B5之间等待3秒

        boolean res3 = pushB5(macId);
        if (!res3) return false;

        return true;
    }

    // 下面是pushB2, pushB4, pushB5方法，保持不变...

    public boolean pushB2(String macId) throws MqttException {
        String str = String.format("{\"msgId\":\"2024082217000054\",\"pushTime\":\"2024-08-22T17:15:17\",\"msgIndex\":\"112\",\"deviceType\":\"225\",\"deviceIndex\":\"1\",\"deviceFuncType\":\"178\",\"macId\":\"%s\",\"serialNumber\":\"%s\",\"errorCode\":\"0\",\"issuerIdentifier\":\"BDADCBD532010001\",\"contractType\":\"0\",\"contractVersion\":\"64\",\"dateofIssue\":\"20230531\",\"dateofExpire\":\"20280530\",\"equitmentCV\":\"16\",\"obuStatus\":\"8193\",\"positionStatus\":\"1\",\"obuPosition\":\"FFFFFFDC00000238\",\"antennaID\":\"1\"}", macId, RandomUtil.generateRandomCode());
        mqttPushClient.publish(false, String.format("E/14/G0055/G0055140440/14012401/%s/Push/DevInfo/Rsu", hex), str);
        return true;
    }

    public boolean pushB4(String macId, String str15, String str19, String ef01, String ef04) throws MqttException {
        JSONObject json = new JSONObject();
        String str = String.format("{\"msgId\":\"2025011017000026\",\"pushTime\":\"2025-01-10T17:40:54\",\"msgIndex\":\"128\",\"deviceType\":\"225\",\"deviceIndex\":\"1\",\"deviceFuncType\":\"180\",\"macId\":\"%s\",\"serialNumber\":\"%s\",\"errorCode\":\"0\",\"authMode\":\"0\",\"eandom\":\"\",\"algorithmID\":\"0\",\"cardStatus\":\"0\",\"cardRestMoney\":\"2147446787\",\"readEF04Status\":\"0\",\"vehicleInfoCostTime\":\"99\",\"cpuCostTime\":\"95\",\"ef04CostTime\":\"50\"}", macId, RandomUtil.generateRandomCode());
        json = JSONObject.parseObject(str);
        json.put("vehicleInfo", ef01);
        json.put("issuerInfo", str15);
        json.put("lastStation", str19);
        json.put("ef04Info", ef04);

        mqttPushClient.publish(false, String.format("E/14/G0055/G0055140440/14012401/%s/Push/DevInfo/Rsu", hex), json.toString());

        return true;
    }

    public boolean pushB5(String macId) throws MqttException {
        String str = String.format("{\"msgId\":\"2024082217000056\",\"pushTime\":\"2024-08-22T17:15:18\",\"msgIndex\":\"144\",\"deviceType\":\"225\",\"deviceIndex\":\"1\",\"deviceFuncType\":\"181\",\"macId\":\"%s\",\"serialNumber\":\"%s\",\"errorCode\":\"0\",\"psamNo\":\"123456789ABC\",\"transTime\":\"20240822171517\",\"transType\":\"9\",\"tac\":\"A6CEFAF6\",\"iccPaySerial\":\"39\",\"psamTransSerial\":\"1021212\",\"cardBalance\":\"2147446786\",\"algorithmId\":\"0\",\"mac2\":\"44430D06\",\"keyVersion\":\"1\",\"writeEF04Status\":\"0\"}", macId, RandomUtil.generateRandomCode());
        mqttPushClient.publish(false, String.format("E/14/G0055/G0055140440/14012401/%s/Push/DevInfo/Rsu", hex), str);
        return true;
    }
}